package com.hjy.hjyojbackendjudgeservice.judge.rabbitMq;

import com.hjy.hjyojbackendjudgeservice.judge.JudgeService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @version 1.0
 * @Author HJY_Maker
 * @Date 2024/7/8 星期一 21:51
 */
@Component
@Slf4j
public class MqMessageConsumer {
    //指定程序监听的消息队列和确认机制,第一个参数是队列名称，第二个是 是否手动确认消息。
    @Resource
    private JudgeService judgeService;

    @SneakyThrows
    @RabbitListener(queues = {"OjMqConstant.OJ_QUEUE_NAME"}, ackMode = "MANUAL")
    public void receiveMessage(String message,
                               Channel channel,
                               @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receive message: {}", message);
        try {
            Long questionSubmitId = Long.valueOf(message);
            judgeService.dojudge(questionSubmitId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
